//
//  TSLimitConvertViewController.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/11/5.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

class TSLimitConvertViewController: TSBaseViewController {
    
    var tableView : UITableView!
    
    fileprivate var jin_zhong11 : String?
    fileprivate var first_song : String?
    
    lazy var headerView : TSLimitConvertHeaderView = {
        let tableHeaderView = TSLimitConvertHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 178))
        return tableHeaderView
    }()
    lazy var sectionHeaderView : TSConvertSectionHeaderView = {
        var headerView = TSConvertSectionHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 178))
        headerView.delegate = self
        return headerView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configViews()
        setupNavigationTitle(title: "额度转换")
        requestConvertInfo()
        requestWithdrawRate()
    }
    
}

//MARK: - TSConvertSectionHeaderViewDelegate
extension TSLimitConvertViewController : TSConvertSectionHeaderViewDelegate {
    func converToCoin(money: String, convertType: TSConvertType) {
        convertRequest(money: money, convertType: convertType)
    }
}

//MARK: - UITableViewDelegate
extension TSLimitConvertViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return sectionHeaderView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 178
    }
    
}

//MARK: - UITableViewDataSource
extension TSLimitConvertViewController : UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self))
        
        if cell == nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(UITableViewCell.self))
        }
        
        return cell!
    }
}

//MARK: - Network Request
extension TSLimitConvertViewController {
    
    func requestConvertInfo() {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getconvertInfo, showHUD: true, success: { (data) in
            
            CBToast.hiddenToastAction()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 转换操作提交 */
    func convertRequest(money:String, convertType:TSConvertType) {
        
        CBToast.showToastAction()
        
        var target : TMSNetworkTools!
        
        if convertType == TSConvertType.convertCoin {
            
            target = TMSNetworkTools.convertCashToCoin(money: money)
            
        } else if convertType == TSConvertType.convertCash {
            
            target = TMSNetworkTools.convertCoinToCash(money: money)
            
        } else if convertType == TSConvertType.convertGain  {
            
            target = TMSNetworkTools.convertProfitToGain(money: money)
            
        } else {
            
            target = TMSNetworkTools.convertGainToCash(money: money)
            
        }
        
        TSNetworkManager.request(target, showHUD: true, success: { (data) in
            
            self.requestUserInfo()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 刷新用户信息 */
    func requestUserInfo() {
        
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: true, success: { (data) in
            
            CBToast.hiddenToastAction()
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            CBToast.showToastAction(message: "中转成功")
            self.headerView.refreshHeaaerView()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 获取转化率 */
    func requestWithdrawRate() {
        
        TSNetworkManager.request(TMSNetworkTools.requestWithdrawRate, showHUD: false, success: { (data) in
            
            let responseArray = data as? Array<Any>
            let responseDict = responseArray?.first as? NSDictionary
            
            self.jin_zhong11 = responseDict?["jin_zhong11"] as? String
            
            let first_song = responseDict?["first_song"] as? NSNumber
            let firstSong = NSString(format: "%@", first_song ?? 0)
            
            self.first_song = String(format: "%zd%%", Int(firstSong.floatValue * 100))
            
            self.tableView.tableFooterView = self.createTableFooterView()
            
        }) { (error) in
            
        }
    }
}

//MARK: - Initialize
extension TSLimitConvertViewController {
    func configViews() {
        
        tableView = UITableView.init(frame: .zero, style: .grouped)
        tableView.backgroundColor = WHITE_COLOR
        tableView.delegate = self;
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        tableView.tableHeaderView = headerView
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }

        if #available(iOS 11, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    func createTableFooterView() -> UIView {
        
        let tableFooterView = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 65))
        tableFooterView.backgroundColor = WHITE_COLOR
        
        let titleLabel = UILabel.init()
        titleLabel.text = "温馨提示："
        titleLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#454545")
        titleLabel.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        tableFooterView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(12)
            make.top.equalToSuperview()
        }

        let infoLabel1 =  createLabel(text: String(format: "* 中心钱包转金币钱包每天首次加增%@", self.first_song ?? "0%"), attributed: true)
        tableFooterView.addSubview(infoLabel1)
        infoLabel1.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
        }

        let infoLabel2 = createLabel(text: String(format: "* 金币钱包转中心钱包投注流水大于%@", self.jin_zhong11 ?? "0%"), attributed: true)
        tableFooterView.addSubview(infoLabel2)
        infoLabel2.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel)
            make.top.equalTo(infoLabel1.snp.bottom).offset(8)
        }
        
        return tableFooterView
    }
    
    func createLabel(text:String, attributed:Bool) -> UILabel {
        
        let attribute = NSMutableAttributedString.init(string: text)
        attribute.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.hexadecimalColor(hexadecimal: "#A5A5A5"), NSAttributedString.Key.font:UIFont.systemFont(ofSize: 13, weight: .medium)], range: NSMakeRange(0, text.count))
        
        if attributed {
            attribute.addAttributes([NSAttributedString.Key.foregroundColor:BASE_RED_COLOR], range: NSMakeRange(0, 1))
        }
        
        let label = UILabel.init()
        label.attributedText = (attribute.copy() as! NSAttributedString)
        return label
    }

}
